// 请求封装
import { baseUrl, navigateTo } from '@/utils/index.ts'

// 请求拦截器
const requestInterceptor = (config: any) => {
  // 添加认证相关的请求头
  const token = uni.getStorageSync('token')
  if (token) {
    config.header = {
      ...config.header,
      'Authorization': `Bearer ${token}`
    }
  }
  
  return config
}

// 响应拦截器
const responseInterceptor = (response: any) => {
  // 可以在这里统一处理响应
  return response
}

// 请求失败拦截器
const failInterceptor = (fail: any) => {
  // 统一处理请求失败
  console.error('请求失败:', fail)
  return Promise.reject(fail)
}

interface RequestOptions {
  url: string
  method?: 'GET' | 'PUT' | 'POST' | 'DELETE'
  data?: any
  header?: any
}

interface ResponseData {
  code: number
  message: string
  data: any
}

// 封装请求方法
const request = (options: RequestOptions): Promise<ResponseData> => {
  let config = { ...options }
  
  // 设置默认值
  config.method = config.method || 'GET'
  config.data = config.data || {}
  config.header = {
    'Content-Type': 'application/json',
    ...config.header
  }
  
  // 请求拦截
  config = requestInterceptor(config)
  
  return new Promise((resolve, reject) => {
    uni.request({
      url: baseUrl + config.url,
      method: config.method,
      data: config.data,
      header: config.header,
      success: (res: any) => {
        // 响应处理
        const response = responseInterceptor(res)
        // 后端返回格式为 {code: number, message: string, data: any}
        const result = response.data

        // 根据后端返回的状态码进行处理
        if (response.statusCode === 200) {
          // 成功状态
          if (result.code === 200) {
            // 业务逻辑成功
            resolve(result)
          } else {
            // 业务逻辑失败
            uni.showToast({
              title: result.msg || '请求失败',
              icon: 'none'
            })
            reject(result)
          }
        } else if (response.statusCode === 401) {
          // 未授权，token过期或无效
          uni.showToast({
            title: result.msg,
            icon: 'none'
          })
          
          // 清除本地存储的用户信息
          uni.removeStorageSync('userInfo')
          uni.removeStorageSync('token')
          
          // 跳转到登录页
          navigateTo('/pages/auth/auth', 'navigate')
          
          reject(response)
        } else {
          // HTTP错误
          uni.showToast({
            title: result.msg,
            icon: 'none'
          })
          reject(response)
        }
      },
      fail: (err) => {
        // 失败处理
        const fail = failInterceptor(err)
        uni.showToast({
          title: err.errMsg || '请求失败',
          icon: 'none'
        })
        reject(fail)
      }
    })
  })
}

export default request